package io.github.fb513.api.facade;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.github.fb513.api.entity.User;
import io.github.fb513.api.entity.UserOnline;
import io.github.fb513.api.enums.ActiveUserStatusEnum;
import io.github.fb513.api.enums.RespMetaEnum;
import io.github.fb513.api.exception.WebBaseException;
import io.github.fb513.api.model.request.LoginReq;
import io.github.fb513.api.model.request.UserReq;
import io.github.fb513.api.model.response.UserInfoResp;
import io.github.fb513.api.service.IUserOnlineService;
import io.github.fb513.api.service.IUserService;
import io.github.fb513.common.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author fengbo
 * @since 2023/12/25 9:07
 */
@Component
public class UserFacade {

    @Autowired private IUserService userService;
    @Autowired private IUserOnlineService userOnlineService;

    public Map<String, Object> generateUserToken(LoginReq req) {
        User user = userService.getOne(new LambdaQueryWrapper<User>().select(User::getId)
                .eq(User::getAppId, req.getAppId()).eq(User::getBizId, req.getUserId()).last("limit 1"));
        if (user == null) {
            throw new WebBaseException(RespMetaEnum.NO_USER);
        }
        UserOnline onlineUser = userOnlineService.getOne(new LambdaQueryWrapper<UserOnline>()
                .select(UserOnline::getId, UserOnline::getActiveStatus)
                .eq(UserOnline::getUserId, user.getId()).eq(UserOnline::getClientType, 1));
        if (onlineUser == null) {
            onlineUser = new UserOnline();
            onlineUser.setUserId(user.getId());
            onlineUser.setClientType(1);
        } else if (ActiveUserStatusEnum.LOGINED.getCode().equals(onlineUser.getActiveStatus())
                || ActiveUserStatusEnum.ONLINE.getCode().equals(onlineUser.getActiveStatus())) {
            // TODO 处理重复登录
        }
        onlineUser.setActiveStatus(ActiveUserStatusEnum.LOGINED.getCode());
        userOnlineService.saveOrUpdate(onlineUser);
        String token = JwtUtils.createToken(Map.of("userId", user.getId(), "clientType", 1));
        return Map.of("token", token, "userId", user.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveUserBatch(List<UserReq> reqList) {
        List<User> userList = new ArrayList<>(reqList.size());
        for (UserReq userReq : reqList) {
            userList.add(convertUserReqToUser(userReq));
        }
        if (!CollectionUtils.isEmpty(userList)) {
            userService.saveBatch(userList);
        }
    }

    private User convertUserReqToUser(UserReq userReq) {
        User user = new User();
        user.setAppId(userReq.getAppId());
        user.setBizId(userReq.getUserId());
        user.setNickName(userReq.getNickName());
        user.setUserSex(userReq.getUserSex());
        return user;
    }

    public UserInfoResp getUserInfo(Long userId) {
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .select(User::getNickName, User::getAvatarUrl)
                .eq(User::getId, userId).last("limit 1"));
        if (user == null) {
            throw new WebBaseException(RespMetaEnum.NO_USER);
        }
        UserInfoResp userInfoResp = new UserInfoResp();
        userInfoResp.setNickName(user.getNickName());
        userInfoResp.setAvatarUrl(user.getAvatarUrl());
        return userInfoResp;
    }

}
